package com.example.NIO.zerocopy;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;

public class NewIOClient {
    public static void main(String[] args) throws IOException {
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.connect(new InetSocketAddress("localhost", 7001));
        String filename = "541118 深入理解计算机系统（原书第三版）.pdf";
        //得到个文件channel
        FileChannel fileChannel = new FileInputStream(filename).getChannel();
        // 准备发送
        long start = System.currentTimeMillis();

        // 在 linux 下，一个 trsferTo 发送就可以完成
        // 在 windows 下，依次调用 trasferTo，只能发送 8 m,就需要分段传输文件，而且
        // 要注意传输时的位置
        // traferTo 底层使用到 零拷贝
        int chunk = 8388608; // 8M
        int position = 0;
        long transferCount = 0;
        while (position <= fileChannel.size()) {
            transferCount += fileChannel.transferTo(position, chunk, socketChannel);
            position += chunk;
            if (position < fileChannel.size() && (position + chunk) > fileChannel.size()) {
                transferCount += fileChannel.transferTo(position, fileChannel.size() - position, socketChannel);
                break;
            }

        }
//        long transferCount = fileChannel.transferTo(0, fileChannel.size(), socketChannel);
        System.out.println("发送的总的字节数 = " + transferCount + "耗时：" +
                (System.currentTimeMillis() - start));
        // 关闭
        fileChannel.close();
        socketChannel.close();
    }
}
